//max:'10mb' 可用单位b, kb, mb, gb, tb 
//extensions:'jpeg,gif,png' 可上传文件扩展名
//label:'上传附件' 按钮名称
//removable:true 是否可删除
//single:false 是否单选
//uploadable:true 是否看上传  查看页面这里设为false即可
(function($){
	$.fn.upload=function(options){
		var uploadPath="/file/upload.do";
		var linksPath="/file/links.do";
		var downloadPath="/file/download.do";
		var files=[];
		if(typeof(options)=='string'&&options=='getFiles'){
			var data=$(this).data();
			for(var p in data){
				files[files.length]=data[p];
			}
			return files;
		}
		var UUID = {
			toString:function(len, radix) {
				var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''), uuid = [], i;
				radix = radix || chars.length;
				if (len) {
					for (i = 0; i < len; i++)
						uuid[i] = chars[0 | Math.random() * radix];
				} else {
					var r;
					uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
					uuid[14] = '4';
					for (i = 0; i < 36; i++) {
						if (!uuid[i]) {
							r = 0 | Math.random() * 16;
							uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
						}
					}
				}
				return uuid.join('');
			}
		};
		var uuid=UUID.toString();

		var opt=$.extend({
			max:'100mb',
			extensions:'*',
			label:'上传附件',
			removable:true,
			single:false,
			uploadable:true
		},options);
		var $this=this;
		function init(){
			var uploader=$('<div id="view'+uuid+'">你的浏览器不支持该上传组件</div>'+
				'<div id="container'+uuid+'" class="container">'+
				'</div>');
			if(opt.uploadable){
				uploader.last().append('<a id="pickfiles'+uuid+'" href="javascript:;"class="l-btn l-btn-small" data-options="iconCls:\'icon-add\'" group=""><span class="l-btn-left l-btn-icon-left"><span class="l-btn-text">'+opt.label+'</span><span class="l-btn-icon icon-add">&nbsp;</span></span></a>');
			}else{
				uploader.last().append('<a style="display:none" id="pickfiles'+uuid+'" href="javascript:;"class="l-btn l-btn-small" data-options="iconCls:\'icon-add\'" group=""><span class="l-btn-left l-btn-icon-left"><span class="l-btn-text">'+opt.label+'</span><span class="l-btn-icon icon-add">&nbsp;</span></span></a>');
			}
			uploader.appendTo(this);
			var uploader = new plupload.Uploader({
				runtimes : 'html5,flash,silverlight,html4',
				browse_button : 'pickfiles'+uuid, 
				container: document.getElementById('container'+uuid), 
				url : uploadPath,
				flash_swf_url : '../plupload/Moxie.swf',
				silverlight_xap_url : '../plupload/Moxie.xap',
				multi_selection:!opt.single,
				filters : opt.filters,
				filters : {
					max_file_size : opt.max,
					mime_types: [
						{title : "files", extensions : opt.extensions}
					]
				},
				init: {
					PostInit: function() {
						$('#view'+uuid).html('');
						links.call($this,uploader);
					},
					FilesAdded: function(up, files) {
						plupload.each(files, function(file) {
							if(opt.single){
								$.each(uploader.files,function(file){
									uploader.removeFile(file);
									//$('#filelist').html('');
									$(opt.area).html('');
									$($this).removeData(file.id);
								});
							}
							var $fileItem=$('<div id="' + file.id + '"><a href="javascript:;" class="download-link">' + file.name + ' (' + plupload.formatSize(file.size) + ')</a><b></b>&nbsp;</div>')
							if(opt.removable){
								$('<a href="javascript:;">删除</a>').on('click',function(){
									var $item=$(this).parent('div');
									var f=uploader.getFile($item.attr('id'));
									if(f) uploader.removeFile(f);
									$item.remove();
									$($this).removeData(f.id);
								}).appendTo($fileItem);
							}
							$fileItem.appendTo(opt.area);
						});
						uploader.start();
					},
					UploadProgress: function(up, file) {
						document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>";
					},
					FileUploaded:function(up,file,res){
						var obj=$.parseJSON(res.response);
						if(obj.data.code<0){
							return top.$alert(err.message);
						}
						$($this).data(file.id,obj.data);
						$('#'+file.id).find('a[class="download-link"]').attr('href',downloadPath+'?id='+obj.data.id);
					},
					Error: function(up, err) {
						//上传失败错误提示
						top.$alert(err.message);
					}
				}
			});
			uploader.init();
			return uploader;
		}
		
		function links(up){
			if(opt.links!=null&&opt.links.type!=null&&opt.links.bid!=null){
				$.post(linksPath,opt.links,function(files){
					for(var i in files){
						$($this).data(files[i].id,files[i]);
						var $listitem=$('<div id="' + files[i].id + '"><a href="'+downloadPath+'?id='+files[i].id+'">' + files[i].name + ' (' + plupload.formatSize(files[i].length) + ')</a><b></b>&nbsp;</div>');
						if(opt.removable){
							$('<a href="javascript:;">删除</a>').on('click',function(){
								var $item=$(this).parent('div');
								$($this).removeData($item.attr('id'));
								$item.remove();
							}).appendTo($listitem);
						}
						$listitem.appendTo('#fileArea');
					}
				});
			}
		}
		init.call(this);
	};
	
})(jQuery);

function showUpload(options) {
	options = $.extend(options,{uri:'/file/upload.do',width:800,height:460});
	show(options);
}